package com.zzxx.exam.service;

import com.zzxx.exam.entity.*;
import com.zzxx.exam.ui.ClientContext;
import com.zzxx.exam.ui.LoginFrame;
import com.zzxx.exam.ui.MenuFrame;
import com.zzxx.exam.ui.WelcomeWindow;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.TimerTask;

/** 软件的核心功能：登陆，开始(发卷)，交卷... */
public class Controller {
    /**
     * login()
     *
     * createPaper()
     *
     * 上一题
     *
     * 下一题
     *
     * 交卷
     *
     * 计算分数
     */

    private ClientContext clientContext;
    private EntityContext entityContext;
    private User user;
    private int score;
    private boolean finished = false;
    private boolean started = false;

    private ArrayList<QuestionInfo> paper = new ArrayList<>();

    /**切换界面*/
    public void switchView(JFrame loginFrame, JFrame menuFrame) {
        loginFrame.setVisible(false);
        menuFrame.setVisible(true);
    }

    public void saveUserAnswers(int index, List<Integer> userAnswers) {
        QuestionInfo questionInfo = paper.get(index);
        questionInfo.getUserAnswers().clear();
        questionInfo.getUserAnswers().addAll(userAnswers);
    }

    /**延迟切换界面*/
    public void delayswitchView(JWindow welcomeWindow, JFrame loginFrame) {
        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                welcomeWindow.setVisible(false);
                loginFrame.setVisible(true);
            }
        }, 1500);
    }

    /**登陆操作----通过ID判断是否登录成功，成功则返回用户对象*/
    public User login(Integer id, String password) throws IdAndPasswordException {
        User user = entityContext.getUserById(id);
        if (user == null){
            //JOptionPane.showMessageDialog(new JOptionPane(),"用户名为空或密码不正确","错误",JOptionPane.WARNING_MESSAGE);
            throw new IdAndPasswordException("用户名不正确");
        } else if (!user.getPassword().equals(password)) {
            //JOptionPane.showMessageDialog(new JOptionPane(),"密码为空或密码不正确","错误",JOptionPane.WARNING_MESSAGE);
            throw new IdAndPasswordException("密码不正确");
        }else {
            this.user = user;
            return user;
        }
    }

    public ExamInfo satrtExam() {
        if (finished)
            throw new RuntimeException("考试已经结束");
        if(started)
            throw new RuntimeException("考试已经开始");

        createPaper();

        ExamInfo examInfo = new ExamInfo();
        examInfo.setTitle(entityContext.getPaperTitle());
        examInfo.setTimeLimit(entityContext.getTimeLimit());
        examInfo.setUser(user);
        examInfo.setQuestionCount(paper.size());

        started = true;
        return examInfo;
    }

    public int examOver() {
        if (finished)
            throw new RuntimeException("考试已经结束");
        for (QuestionInfo q : paper) {
            Question question = q.getQuestion();
            List<Integer> userAnswers = q.getUserAnswers();
            if (userAnswers.equals(question.getAnswers())){
                score += question.getScore();
            }
        }
        finished = true;
        return score;
    }


    private void createPaper() {
        Random ran = new Random();
        int index = 0;
        for (int level = Question.LEVEL1; level <= Question.LEVEL10; level++) {
            List<Question> questions = entityContext.getQuestionsById(level);
            int i1 = ran.nextInt(questions.size());
            Question q1 = questions.remove(i1);
            QuestionInfo qi1 = new QuestionInfo(index++, q1);

            int i2 = ran.nextInt(questions.size());
            Question q2 = questions.remove(i2);
            QuestionInfo qi2 = new QuestionInfo(index++, q2);

            paper.add(qi1);
            paper.add(qi2);
        }
    }

    public QuestionInfo getFirstQustion() {
        return paper.get(0);
    }

    public QuestionInfo getQuestion(int i) {
        return paper.get(i);
    }

    public String showMsg() {
        String msg = entityContext.getMsg();
        msg = msg.substring(1, msg.length() - 2);
        msg = msg.replaceAll(" ", "");
        return msg.replaceAll(",","");
    }


    public void setClientContext(ClientContext clientContext) {
        this.clientContext = clientContext;
    }

    public void setEntityContext(EntityContext entityContext) {
        this.entityContext = entityContext;
    }

    public boolean isFinished() {
        return finished;
    }

    public boolean isStarted() {
        return started;
    }
}
